package com.unidt.www.framework.common.util.object;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

import java.util.*;

/**
 * @Author sk
 * @Description:
 * @Date 2022/9/5 10:04
 **/
@Slf4j
public class ConvertUtil {


    public static <T> List<T> convertList(List<?> list, Class cls) {

        List l = new ArrayList();

        if (list == null || list.isEmpty()) {
            return new ArrayList();
        } else {
            list.forEach(e -> {
                Object o = null;
                try {
                    o = cls.newInstance();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                BeanUtils.copyProperties(e, o);
                l.add(o);
            });
        }
        return l;
    }

    public static <T> T convert(Object src, Class cls) {
        Object o = null;
        try {
            if (Objects.nonNull(src)) {
                o = cls.newInstance();

                BeanUtils.copyProperties(src, o, getNullPropertyNames(src));
                return (T) o;
            }

        } catch (Exception e) {
            log.error("convert error", e);
        }
        return null;
    }


    public static String[] getNullPropertyNames(Object source) {
        final BeanWrapper src = new BeanWrapperImpl(source);
        java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

        Set<String> emptyNames = new HashSet<>();
        for (java.beans.PropertyDescriptor pd : pds) {
            Object srcValue = src.getPropertyValue(pd.getName());
            if (srcValue == null) {
                emptyNames.add(pd.getName());
            }
        }

        String[] result = new String[emptyNames.size()];
        return emptyNames.toArray(result);
    }

    public static   void  copyProperties(Object src,Object target){
        if (Objects.nonNull(src)) {
            BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
        }
    }
}
